package com.zl.csMall.mine.user.controller;

import com.alibaba.fastjson2.JSONObject;
import com.zl.csMall.code.LoginCacheMap;
import com.zl.csMall.code.constant.EntiretyConstant;
import com.zl.csMall.mine.user.po.User;
import com.zl.csMall.mine.user.service.UserService;
import com.zl.csMall.mine.user.vo.LoginParamsVo;
import com.zl.csMall.mine.user.vo.LoginResultVo;
import com.zl.csMall.mine.user.vo.MerchantLoginParamsVo;
import com.zl.csMall.util.SecretUtil;
import com.zl.csMall.util.Util;
import com.zl.csMall.util.WechatUtil;
import com.zl.csMall.vo.ReturnModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @description: LoginController
 * @author: ChenNing
 * @date 2025-10-22 15:33
 */
@Slf4j
@CrossOrigin(origins = "*")
@Api(tags = "登录")
@RestController
@RequestMapping("csMall/login")
public class LoginController {

    @Value("${CUSTOM.DOMAIN-NAME}")
    private String DOMAIN_NAME;
    @Autowired
    private WechatUtil wechatUtil;
    @Autowired
    private UserService userService;

    private final LoginCacheMap loginCacheMap;

    public LoginController(LoginCacheMap loginCacheMap) {
        this.loginCacheMap = loginCacheMap;
    }


    /**
     * @description: 用户登录
     * @author ChenNing
     * @date: 2025-10-22 15:42
     */
    @CrossOrigin("*")
    @ApiOperation(value = "用户登录")
    @PostMapping
    public ReturnModel login(@Validated @RequestBody LoginParamsVo loginParamsVo){
        String openId = wechatUtil.getOpenId(loginParamsVo.getCode());
        if (Util.isNullOrEmpty(openId)){
            return new ReturnModel(false, "openId获取失败！");
        }

        Date date = new Date();
        String token = Util.getRandomToken();
        LoginResultVo loginResultVo = null;
        // 查询用户
        User user = userService.getByOpenId(openId);
        if (user == null){
            user = new User();
            // 首次登录 - 创建用户实体
            user.setId(Util.getUuId());
            user.setOpenId(openId);
            user.setWxAvatarUrl(DOMAIN_NAME + "avatar.jpg");
            user.setLoginDate(date);
            user.setName(EntiretyConstant.CREATE_USER_DEFAULT_NAME);
            user.setIsAdmin(2);
            user.setCreateDate(date);
            user.setUpdateDate(date);
            boolean result = userService.save(user);
            if (!result){
                return new ReturnModel(false, "用户创建失败！");
            }
            user.setPwdkey(null);
            user.setOpenId(null);
            loginResultVo = new LoginResultVo(token, user);
        } else {
            // 已有账号 - 更新用户信息
            user.setLoginDate(date);
            user.setWxAvatarUrl(DOMAIN_NAME + "avatar.jpg");
            userService.updateById(user);
            user.setPwdkey(null);
            user.setOpenId(null);
            loginResultVo = new LoginResultVo(token, user);
        }
        loginCacheMap.addUser(token, user);
        return new ReturnModel(loginResultVo);
    }

    /**
     * @description: 商家登录
     * @author ChenNing
     * @date: 2025-10-23 14:27
     */
    @CrossOrigin("*")
    @ApiOperation(value = "商家登录")
    @PostMapping("mer")
    public ReturnModel merchantLogin(@Validated @RequestBody MerchantLoginParamsVo merchantLoginParamsVo){
        User user = userService.getByUsername(merchantLoginParamsVo.getUsername());
        if (user == null){
            return new ReturnModel(false, "用户不存在！");
        }
        if (user.getIsAdmin() == null || user.getIsAdmin() != 1){
            return new ReturnModel(false, "非管理员登录！");
        }
        // 密码校验
        String password = null;
        try {
            password = SecretUtil.encrypt(merchantLoginParamsVo.getPassword(), SecretUtil.stringToKey(user.getPwdkey()));
        } catch (Exception e) {
            log.error("ZL - CHENNING【登录校验】参数传入密码加密异常！PARAMS:" + JSONObject.toJSONString(merchantLoginParamsVo) + " --ERROR:" + e.getMessage(), e);
            return new ReturnModel(false, "", "密码校验异常！");
        }
        if (password != null && password.equals(user.getPassword())){
            user.setPwdkey(null);
            user.setPassword(null);
            user.setOpenId(null);
            String token = Util.getRandomToken();
            loginCacheMap.addUser(token, user);
            // 更新登录时间
            user.setLoginDate(new Date());
            user.setIsAdmin(null);
            userService.updateById(user);
            return new ReturnModel(new LoginResultVo(token, user));
        }
        return new ReturnModel(false, "", "密码错误！");
    }


}
